package dao.implDao;

import model.Gift;
import model.User;
import org.hibernate.Session;
import util.HibernateUtil;

import java.sql.SQLException;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * Created with IDEA.
 * User: Ѱ
 * Date: 26.07.14
 * Time: 13:35
 */
public class FriendsDao {


    public void addFriend(User user, User friend) throws SQLException {
        List<User> friendList = new LinkedList<User>();

        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            User tmp =(User) session.load(User.class,user.getId());
            friendList = tmp.getFriends();
            friendList.add(friend);
            user.setFriends(friendList);
            session.update(user);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deleteFriend(User user,User friend)throws SQLException{
        List<User> friendList = new LinkedList<User>();

        try {Session session = null;


            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            if (user.getFriends() !=null){
                friendList = session.createCriteria(User.class).list();
                friendList.remove(friend);
                user.setFriends(friendList);
            }else System.out.println("The friends not found");
            session.update(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
            /**Метод для добавления подарка добавим сюда, дабы не писать отдельный класс*/

    public void addGifts (User user, Gift gift)throws SQLException{
        List<Gift> giftList = new LinkedList<Gift>();

        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            if (user.getFriends() != null) {
                giftList = session.createCriteria(User.class).list();
                giftList.add(gift);
                user.setGifts(giftList);
            } else {
                giftList.add(gift);
                user.setGifts(giftList);
            }
            session.update(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}